// 配置跨域
package middleware

import (
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func Cors() gin.HandlerFunc {
	cfg := cors.Config{
		// AllowOrigins: []string{"https://foo.com"},//允许指定源访问
		// AllowAllOrigins: true, //允许所有源的访问（为true时AllowCredentials会失效）
		AllowOriginFunc: func(origin string) bool {
			return true
		}, //允许所有源的访问（解决AllowCredentials失效问题）
		// AllowOriginFunc: func(origin string) bool {
		// 	return origin == "https://github.com"
		// },
		AllowMethods: []string{"POST", "PUT", "GET", "DELETE", "OPTIONS", "UPDATE", "PATCH"},
		AllowHeaders: []string{"Origin", "X-Requested-With", "Content-Type", "Accepte", "Authorization", "Token"}, //允许客户端请求头发送的字段
		// ExposeHeaders:    []string{"Content-Length"},                                                                  //允许客户端响应头读取的字段
		AllowCredentials: true, //允许在跨域请求中携带Cookie等凭证信息

		MaxAge: 12 * time.Hour,
	}
	return cors.New(cfg)
}
